package com.purong.purong.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import com.yao.component.pictureselector.MediaSelector;

import java.io.File;
import java.util.List;

/**
 * Created by wenjiezeng on 2017/11/13.
 */
public class TakePictureUtil {
    private static final int CAMERA_PICTURE = 1000;
    private static final int CAMERA_CUT_PICTURE = 1001;
    private static final int ALBUM_PICTURE = 1002;
    private static final int ALBUM_CUT_PICTURE = 1003;

    private OnTakePictureListenr mListener;
    private Activity mActivity;
    private File TEMP_PATH;
    private String mFileName;
    private String mFileCropName;
    private int mAspectX = 1;
    private int mAspectY = 1;
    private boolean needCut=false;//是否需要裁剪
    public  TakePictureUtil(Activity activity,OnTakePictureListenr listenr){
        this.mActivity=activity;
        this.mListener=listenr;
        TEMP_PATH = getCacheDir(activity, "takePicture");
        if (TEMP_PATH.exists()){
            boolean b=deleteDir(TEMP_PATH);
            if (b)
                TEMP_PATH.mkdirs();
        }else {
            TEMP_PATH.mkdirs();
        }
    }

    public void needCut(boolean b){
        this.needCut=b;
    }
    private  boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            if (children!=null){
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }

        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    private  File getCacheDir(Context context, String uniqueName) {
        String cachePath;
        if ( !Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && !isExternalStorageRemovable()){
            cachePath=context.getCacheDir().getPath();
        }else {
            cachePath=getExternalCacheDir(context)!=null?getExternalCacheDir(context).getPath():context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }
    private boolean isExternalStorageRemovable() {
        return Build.VERSION.SDK_INT >= 9?Environment.isExternalStorageRemovable():true;
    }
    private File getExternalCacheDir(Context context) {
        if(Build.VERSION.SDK_INT >= 8) {
            return context.getExternalCacheDir();
        } else {
            String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
            return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
        }
    }
    /**
     * 拍照
     */
    public void camera() {
        mFileName = "temp_" + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(TEMP_PATH, mFileName);
        if (file.exists()) {
            file.delete();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        mActivity.startActivityForResult(intent, CAMERA_PICTURE);
    }
    /**
     * 本地选择图片
     */
    public void album(final int count) {
        MediaSelector mediaSelector = new MediaSelector(mActivity, MediaSelector.SELECT_PICTURE,count,count==1?true:false, new MediaSelector.onPictureSelectListener() {
            @Override
            public void onSelect(List<String> selectPath) {
                //设置需要裁剪时，只有单张图片会进行裁剪
                if (needCut&&count==1){
                    if (selectPath!=null&&selectPath.size()>0){
                        getSmallFromaAblum(new File(selectPath.get(0)));
                    }
                }else {
                    if (mListener!=null){
                        mListener.onAlbumResult(selectPath);
                    }
                }


            }

            @Override
            public void onCancel() {

            }
        });
        mediaSelector.show();
    }
    /**
     * 拍照返回裁剪
     *
     *
     */
    private void getSmallFromCamera() {
        mFileCropName="temp_crop_" + System.currentTimeMillis() + ".jpg";
        Uri uri = Uri.fromFile(new File(TEMP_PATH, mFileName));
        Uri uri_crop = Uri.fromFile(new File(TEMP_PATH, mFileCropName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        if (mAspectX != -1 && mAspectY != -1) {
            intent.putExtra("aspectX", mAspectX);
            intent.putExtra("aspectY", mAspectY);
        }
        intent.putExtra("scale", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_crop);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, CAMERA_CUT_PICTURE);
    }
    /**
     * 本地选择返回裁剪
     *
     *
     */
    private void getSmallFromaAblum(File mFlie) {
        mFileCropName="temp_crop_" + System.currentTimeMillis() + ".jpg";
        Uri uri = Uri.fromFile(mFlie);
        Uri uri_crop = Uri.fromFile(new File(TEMP_PATH, mFileCropName));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        if (mAspectX != -1 && mAspectY != -1) {
            intent.putExtra("aspectX", mAspectX);
            intent.putExtra("aspectY", mAspectY);
        }
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri_crop);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        mActivity.startActivityForResult(intent, ALBUM_CUT_PICTURE);
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CAMERA_PICTURE:
                    if (!needCut){
                        if (mListener != null) {
                            mListener.onCameraResult(new File(TEMP_PATH,mFileName));
                        }
                    }else {
                        getSmallFromCamera();
                    }
                    break;
                case CAMERA_CUT_PICTURE:
                    if (mListener != null) {
                        mListener.onCameraCutResult(new File(TEMP_PATH,mFileCropName));
                    }
                    break;
                case ALBUM_CUT_PICTURE:
                    if (mListener != null) {
                        mListener.onAlbumCutResult(new File(TEMP_PATH,mFileCropName));
                    }
                    break;

            }
        }else {
            if (mListener!=null){
                mListener.onFail();
            }
        }
    }

    public interface OnTakePictureListenr{
        void onCameraResult(File file);
        void onAlbumResult(List<String> files);
        void onAlbumCutResult(File file);

        void onCameraCutResult(File file);
        void onFail();
    }
}
